
const { Op, Blog } = require("../module");

async function fn_add(ctx) {
    let obj = ctx.request.body;
    obj.time = '2022-5-11';
    console.log(obj);
    Blog.create(obj);
    ctx.body = {
        code: 1000,
        data: '',
        message: "添加成功"
    }
}

async function fn_delete(ctx) {
    let id = ctx.params.id;
    Blog.destroy({
        where: {
            id: id
        }
    });
    ctx.body = {
        code: 1000,
        data: '',
        message: "删除成功"
    }
}

async function fn_alert(ctx) {
    let id = ctx.params.id;
    let obj = ctx.request.body;
    Blog.update(obj, {
        where: {
            id: id
        }
    });
    ctx.body = {
        code: 1000,
        data: '',
        message: "修改成功"
    }
}
async function fn_select(ctx) {
    console.log("sb");
    let bool = ctx.params.id;
    let id = ctx.request.body.id;
    console.log(id);
    if (bool === 'true') {
        let arr = await Blog.findAll({
            order: ['id'],
            where: { id: id }
        });
        console.log(arr);
        ctx.body = {
            code: 1000,
            data: arr,
            message: "获取成功"
        }

    }
    
    else {
        let Value = ctx.request.body.Value;
        console.log(Value);
        if (Value) {
            let arr = await Blog.findAll({
                order: ['id'],
                where: {
                    [Op.or]: {
                        id: isNaN(Value) ? 0 : parseInt(Value),
                        title: isNaN(Value) ? Value : '',
                        abstract: isNaN(Value) ? Value : '',
                        content: isNaN(Value) ? Value : '',
                        classify: isNaN(Value) ? Value : '',
                        author: isNaN(Value) ? Value : '',
                    }
                }
            });
            ctx.body = {
                code: 1000,
                data: arr,
                message: "获取成功"
            }
        }
        else {
            ctx.body = {
                code: 404,
                data: '',
                message: "获取失败"
            }
        }
    }
}
async function fn_List(ctx) {
    let arr = await Blog.findAll({
        order: ['id']
    });
    ctx.body = {
        code: 1000,
        data: arr,
        message: "获取成功"
    }
}


module.exports = {
    'get /Blog': fn_List,
    'post /Blog/:id': fn_select,
    'post /Blog': fn_add,
    'delete /Blog/:id': fn_delete,
    'put /Blog/:id': fn_alert,
}